<template>
  <div class="chart-and-data-container">
    <!-- 左侧图表容器 -->
    <div class="chart-container">
      <div ref="chart" class="chart-inner"></div>
    </div>
    
    <!-- 右侧数据表格容器 -->
    <div class="data-table-container">
      <h3>每日行为数据明细</h3>
      <div class="table-scroll-wrapper">
        <table v-if="dailyTableData.length > 0" class="data-table">
          <thead>
            <tr>
              <th>日期</th>
              <th>用户数</th>
              <th>浏览量(PV)</th>
              <th>购买量</th>
              <th>加购量</th>
              <th>收藏量</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in dailyTableData" :key="index">
              <td>{{ item.day }}</td>
              <td>{{ item.userCnt }}</td>
              <td>{{ item.pvCnt }}</td>
              <td>{{ item.buyCnt }}</td>
              <td>{{ item.cartCnt }}</td>
              <td>{{ item.favCnt }}</td>
            </tr>
            <tr class="total-row">
              <td><strong>总计</strong></td>
              <td><strong>{{ totalUser }}</strong></td>
              <td><strong>{{ totalPv }}</strong></td>
              <td><strong>{{ totalBuy }}</strong></td>
              <td><strong>{{ totalCart }}</strong></td>
              <td><strong>{{ totalFav }}</strong></td>
            </tr>
          </tbody>
        </table>
        <p v-else class="no-data">暂无数据</p>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { onMounted, ref, watch, onUnmounted, computed } from 'vue';

export default {
  name: 'DailyTrend',
  props: {
    chartData: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const chart = ref(null);
    let myChart = null;

    // 处理每日数据并按日期排序
    const dailyData = computed(() => {
      if (!props.chartData || props.chartData.length === 0) {
        return [];
      }
      
      // 直接使用后端数据，按日期升序排序
      const sortedData = [...props.chartData].sort((a, b) => {
        return new Date(a.day) - new Date(b.day);
      });
      
      return sortedData;
    });

    // 表格数据（与图表数据相同）
    const dailyTableData = computed(() => {
      return dailyData.value;
    });

    // 计算总计
    const totalUser = computed(() => {
      return dailyTableData.value.reduce((sum, item) => sum + item.userCnt, 0);
    });

    const totalPv = computed(() => {
      return dailyTableData.value.reduce((sum, item) => sum + item.pvCnt, 0);
    });

    const totalBuy = computed(() => {
      return dailyTableData.value.reduce((sum, item) => sum + item.buyCnt, 0);
    });

    const totalCart = computed(() => {
      return dailyTableData.value.reduce((sum, item) => sum + item.cartCnt, 0);
    });

    const totalFav = computed(() => {
      return dailyTableData.value.reduce((sum, item) => sum + item.favCnt, 0);
    });

    const initChart = () => {
      if (!chart.value) return;
      
      // 销毁旧的图表实例（如果存在）
      if (myChart) {
        myChart.dispose();
      }
      
      myChart = echarts.init(chart.value);
      
      const data = dailyData.value;
      
      // 如果没有数据，显示提示
      if (data.length === 0) {
        myChart.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 16
            }
          }
        });
        return;
      }
      
      // 提取日期和各项数据
      const dates = data.map(item => item.day);
      const userData = data.map(item => item.userCnt);
      const pvData = data.map(item => item.pvCnt);
      const buyData = data.map(item => item.buyCnt);
      const cartData = data.map(item => item.cartCnt);
      const favData = data.map(item => item.favCnt);
      
      // 获取容器宽度用于响应式调整
      const { offsetWidth } = chart.value;
      
      const option = {
        title: {
          text: '每日用户行为趋势分析',
          left: 'center',
          textStyle: {
            fontSize: 20
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(param => {
              // 格式化数字显示，添加千分位分隔符
              const value = param.value.toLocaleString();
              result += `${param.seriesName}: ${value}<br/>`;
            });
            return result;
          }
        },
        toolbox: {
          feature: {
            magicType: {
              show: true,
              type: ['line', 'bar'],
              title: { line: '切换为折线图', bar: '切换为柱状图' }
            },
            restore: { show: true, title: '还原' },
            saveAsImage: { show: true, title: '保存为图片', type: 'png' }
          },
          right: 10,
          top: 10
        },
        legend: {
          data: ['用户数', '浏览量(PV)', '购买量', '加购量', '收藏量'],
          bottom: 10,
          type: 'scroll' // 如果系列太多可以滚动
        },
        grid: {
          left: offsetWidth < 600 ? '12%' : '8%',
          right: offsetWidth < 600 ? '12%' : '8%',
          bottom: '15%', // 调整底部间距，因为去掉了dataZoom
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisPointer: {
            type: 'shadow'
          },
          axisLabel: {
            rotate: 45,
            fontSize: offsetWidth < 600 ? 10 : 12
          }
        },
        yAxis: {
          type: 'value',
          name: '次数',
          min: 0,
          axisLabel: {
            formatter: function(value) {
              if (value >= 10000) {
                return (value / 10000).toFixed(1) + '万';
              }
              return value.toLocaleString();
            }
          }
        },
        // 删除了dataZoom配置
        series: [
          {
            name: '用户数',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              width: 3
            },
            itemStyle: {
              color: '#5470c6'
            },
            data: userData
          },
          {
            name: '浏览量(PV)',
            type: 'bar',
            barGap: 0,
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            data: pvData
          },
          {
            name: '购买量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ffd666' },
                { offset: 0.5, color: '#ffc53d' },
                { offset: 1, color: '#ffc53d' }
              ])
            },
            data: buyData
          },
          {
            name: '加购量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#95de64' },
                { offset: 0.5, color: '#73d13d' },
                { offset: 1, color: '#73d13d' }
              ])
            },
            data: cartData
          },
          {
            name: '收藏量',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ff9c6e' },
                { offset: 0.5, color: '#ff7a45' },
                { offset: 1, color: '#ff7a45' }
              ])
            },
            data: favData
          }
        ]
      };
      
      myChart.setOption(option);
    };

    const handleResize = () => {
      if (myChart) {
        myChart.resize();
      }
    };

    onMounted(() => {
      window.addEventListener('resize', handleResize);
      setTimeout(() => {
        initChart();
      }, 100);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      if (myChart) {
        myChart.dispose();
      }
    });

    watch(() => props.chartData, () => {
      if (myChart) {
        setTimeout(() => {
          initChart();
        }, 50);
      }
    }, { deep: true });

    return {
      chart,
      dailyTableData,
      totalUser,
      totalPv,
      totalBuy,
      totalCart,
      totalFav
    };
  }
}
</script>

<style scoped>
.chart-and-data-container {
  display: flex;
  width: 100%;
  gap: 20px;
  height: 100%;
}

.chart-container {
  flex: 3;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chart-inner {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.data-table-container {
  flex: 1;
  min-width: 300px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.data-table-container h3 {
  margin-top: 0;
  margin-bottom: 15px;
  text-align: center;
  color: #333;
}

.table-scroll-wrapper {
  max-height: 500px;
  overflow-y: auto;
  flex: 1;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.data-table th,
.data-table td {
  border: 1px solid #eaeaea;
  padding: 6px 8px;
  text-align: center;
}

.data-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  position: sticky;
  top: 0;
}

.data-table tr:hover {
  background-color: #f5f7fa;
}

.total-row {
  background-color: #e6f7ff;
  font-weight: bold;
}

.total-row td {
  border-top: 2px solid #1890ff;
}

.no-data {
  text-align: center;
  color: #999;
  margin: 20px 0;
}

/* 响应式布局 */
@media (max-width: 968px) {
  .chart-and-data-container {
    flex-direction: column;
  }
}
</style>